<!--
 * @author  dumeng
 调查问卷-问卷问题列表
-->
<template>
  <div class="survey-qustion">
    <el-collapse-transition>
      <div class="search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="search.content"
          placeholder="请输入题干进行搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>问卷问题</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新增</el-button>
        <!--        <el-button class="filter-item" style="margin-left: 10px;" @click="handleImport">导入</el-button>-->
        <el-button class="filter-item" type="primary" style="margin-left: 10px;" @click="$router.back()">返回</el-button>
      </div>
    </div>
    <div class="table">
      <my-table
        :list="list"
        :filter-column="filtercolumn"
        tag="surveyQuestion"
        operationwidth="80"
        :list-loading="listLoading"
        @handleSelectionChange="handleSelectionChange"
      >
        <el-table-column label="操作" fixed="right" align="center" min-width="80" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handlePublish(scope.row)">
              {{ scope.row.status === '启用' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-if="scope.row.questionType!=='WJWTLX_02' && scope.row.questionType!=='WJWTLX_03' && scope.row.questionType!=='WJWTLX_04'" type="text" size="mini" @click="handleJump(scope.row)">配置</el-button>
          </template>
        </el-table-column>
      </my-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="uploadQuesDialogVisible"
      title="上传练习题"
      center
      width="600px"
    >
      <el-row :gutter="20" style="height: 300px;display: flex;align-items: center;justify-content: center;">
        <el-col :span="12">
          <div class="grid-content download">
            <div class="img-con">
              <img src="../images/ques-down.png">
            </div>
            <el-button type="primary" @click="handleDownload">下载模版</el-button>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content upload">
            <div class="img-con">
              <img src="../images/ques-upload.png">
            </div>
            <el-button type="primary" @click="handleUploadQues">上传excel</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogUploadVisible"
      title="上传文件"
      center
      width="500px"
    >
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传.xls,.xlsx
          <span class="downFile" @click="handleDownload">下载模板</span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogUploadVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="submitUpload()">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogUploadErrorTextVisible"
      title="错误信息"
      center
      width="500px"
    >
      <div class="error-text" style="height: 600px;overflow-y: auto">
        <el-row>
          <el-col v-for="(item, index) in uploadErrorList" :key="index" :span="24" style="margin-bottom: 10px;">
            {{ index + 1 }}、{{ item }}
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px;"
          type="primary"
          @click="dialogUploadErrorTextVisible = false"
        >关闭</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="copyErrorText()">复制</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryPage,
  del,
  getDictByCode,
  updateState
} from '../api/question'
import Pagination from '@/components/Pagination'
import permission from '@/directive/permission/index.js'
import MyTable from '@/components/Table'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { getToken } from '@/utils/auth'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'

export default {
  name: 'SurveyQuestion',
  components: { Pagination, MyTable },
  directives: { permission, elDragDialog },
  data() {
    return {
      surveyId: '',
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      search: {
        content: ''
      },
      list: [],
      total: 0,
      multipleSelection: [],
      dict: {
        EXAM_STATE: []
      },
      curEditRow: {},
      /* 上传题库相关*/
      loadingUpload: false,
      uploadQuesDialogVisible: false,
      dialogUploadVisible: false,
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/subjectQuestion/questionImport',
      uploadHeaders: { 'ttsxyhcs': getToken() },
      uploadData: {
        subjectId: this.$route.query.si
      },
      uploadErrorList: [],
      dialogUploadErrorTextVisible: false
      /* 上传题库相关 end*/
    }
  },
  created() {
    if (this.$route.query.si) {
      this.surveyId = this.$route.query.si
    } else {
      this.$message({
        type: 'error',
        message: '参数异常，请重试!',
        onClose: () => {
          this.$router.back()
        }
      })
    }
    this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    /**
     * 相关回答跳转
     */
    handleJump(row) {
      this.$router.push({
        path: this.$filterPath('questionJump'),
        query: { i: row.id }
      })
    },
    /**
     * 创建
     */
    handleCreate() {
      this.$router.push({
        path: this.$filterPath('questionManage'),
        query: { si: this.surveyId }
      })
    },
    /**
     * 修改
     */
    handleUpdate(row) {
      this.$router.push({
        path: this.$filterPath('questionManage'),
        query: { i: row.id, si: this.surveyId }
      })
    },
    /**
     * 启用/禁用
     */
    handlePublish(row) {
      this.$confirm(row.status === '启用' ? '确认禁用？' : '确认启用？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState({ id: row.id, status: row.status === '启用' ? 'ZT02' : 'ZT01' }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    handleImport() {
      this.dialogUploadVisible = true
    },
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/subjectQuestion/downloadQuestionTemplate' + exportSign({}).paramStr
      link.setAttribute('download', '练习题模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleUploadQues() {
      this.dialogUploadVisible = true
    },
    submitUpload() {
      this.$set(this, 'uploadHeaders', importSign(this.uploadHeaders, this.uploadData))
      this.loadingUpload = true
      this.$refs.upload.submit()
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.dialogUploadVisible = false
        this.uploadQuesDialogVisible = false
        this.$refs.upload.clearFiles()
        this.getList()
      } else {
        this.$message.error(data.msg || '网络异常')
        this.$refs.upload.clearFiles()
        if (data.data) {
          this.uploadErrorList = data.data
          this.dialogUploadErrorTextVisible = true
        }
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
    },
    /**
     * 复制错误消息
     */
    copyErrorText() {
      let val = ''
      this.uploadErrorList.forEach(item => {
        val += item + '\n'
      })
      const input = document.createElement('input')
      input.setAttribute('readonly', 'readonly')
      input.setAttribute('value', val)
      document.body.appendChild(input)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message({
          title: '成功',
          message: '复制成功！',
          type: 'success',
          duration: 1500
        })
      }
      document.body.removeChild(input)
    },
    /**
     * 批量删除
     */
    handleDeletes() {
      if (this.multipleSelection.length > 0) {
        const arr = this.multipleSelection.map(item => {
          return item.id
        }).join(',')
        this.deleteData(arr)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    /**
     * 删除
     */
    handleDelete(row) {
      this.deleteData(row.id)
    },

    /**
     * 删除
     * @param ids
     */
    deleteData(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: ids }).then(res => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => {
      })
    },
    /**
     * table 列数据过滤
     * @param scope
     * @param item
     * @returns {string}
     */
    filtercolumn(scope, item) {
      if (item === 'opts') {
        return JSON.parse(scope.row['answer']).opts ? JSON.parse(scope.row['answer']).opts.join('、') : ''
      } else if (item === 'answer') {
        return JSON.parse(scope.row['answer']).answers ? JSON.parse(scope.row['answer']).answers.join('、') : ''
      } else if (item === 'score') {
        return scope.row[item] ? scope.row[item] / 100 : ''
      } else if (item === 'typeValue') {
        return scope.row[item] && scope.row['parentId'] ? '案例-' + scope.row[item] : scope.row[item]
      } else {
        return scope.row[item]
      }
    },
    /**
     * 获取字典
     * @param code
     * @returns {Promise<any>}
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    /**
     * 重置
     */
    resettingBtn() {
      this.listQuery.page = 1
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },
    /**
     * 多选
     */
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    /**
     * 获取列表
     */
    getList(obj) {
      const query = {
        stem: this.search.content,
        dataId: this.surveyId,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total || 0
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    /**
     * 行样式修改
     * @param row
     * @param rowIndex
     * @returns {{padding: string, height: string, background: string}}
     */
    rowClass({ row, rowIndex }) {
      return {
        padding: '5px 0',
        height: '20px',
        background: 'rgba(247,247,248,1)'
      }
    }
  }
}
</script>
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
.survey-qustion {
  padding: 10px 20px 10px 10px;

  .downFile {
    display: inline-block;
    @include font-color($mainColor);
    font-size: 16px;
    float: right;
    text-decoration: underline;
  }

  .downFile:hover {
    cursor: pointer;
  }

  .el-card {
    margin-bottom: 10px;

    .current-position-name {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
  }

  .search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            &.el-date-editor input {
              padding-left: 30px;
            }

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .grid-content {
    text-align: center;

    .img-con {
      margin-bottom: 20px;

      img {
        width: 150px;
      }
    }
  }

  .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
    }
  }

  .btn-container {
    display: flex;
    align-items: center;
    background: #fff;
    margin: 10px 0;
    padding: 0 10px;

    .btn-container-title {
      flex: 1;
      line-height: 46px;
      font-size: 16px;
      color: rgba(51, 51, 51, 1);
      background: #ffffff;
    }
  }
}
</style>
